//
//  regViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-6-16.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "regViewController.h"
#import "regDoneViewController.h"
#import "ZPUserModel.h"

@interface regViewController ()
@property (nonatomic, strong) NSArray *logResult;
@property (strong, nonatomic) IBOutlet UITextField *mobileTF;
@property (strong, nonatomic) IBOutlet UIButton *submitBT;
@property (strong, nonatomic) IBOutlet UITextField *passwdTF;
@property (strong, nonatomic) IBOutlet UIButton *valiBT;
- (IBAction)getValidateCode:(UIButton *)sender;
- (IBAction)submitForm:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UIButton *regBt;

@end

@implementation regViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.backgroundColor = ColorFromRGB(0xF6F6F6);
    self.title = @"注册";
    [self setupBarItem];
    [self setupButton];
}



- (void)setupButton
{
    [_submitBT.layer setCornerRadius:5.0];
    [_submitBT setBackgroundColor:ColorFromRGB(0xff0100)];
    
    NSString *regString = @"我同意，注册协议";
    NSMutableAttributedString *temString = [[NSMutableAttributedString alloc] initWithString:regString];
    
    [temString addAttribute:NSUnderlineStyleAttributeName
                      value:[NSNumber numberWithInt:NSUnderlineStyleThick]
                      range:NSMakeRange(4,4)];
    _regBt.titleLabel.attributedText = temString;
}
- (void)setupBarItem
{
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]
                                            initWithTitle:@"取消"
                                            style:UIBarButtonItemStyleBordered
                                            target:self
                                            action:@selector(dismiss)];
}

- (void)dismiss{
    
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.5;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 14.5, self.tableView.frame.size.width, 0.5)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    return lineV;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0.5)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    return lineV;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (BOOL)validateMobile:(NSString *)userName
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:userName];
}
- (void)getCode{

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"mobile": _mobileTF.text};
[manager POST:APIURL@"ucmembers/getValidateCode.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *backLog = responseObject[@"isSuccess"];
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
}];
}

- (IBAction)getValidateCode:(UIButton *)sender {
    
    NSString *mobileNo = _mobileTF.text;
    if ( [mobileNo length] > 0 && [self validateMobile:mobileNo]) {
        [self getCode];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"请检查手机号码是否正确"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    __block int timeout=120; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //没秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                _valiBT.titleLabel.text = @"获取验证码";
                _valiBT.enabled = YES;
                _valiBT.backgroundColor = [UIColor greenColor];
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"%d",timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                 _valiBT.titleLabel.text = strTime;
//                [_valiBT sizeToFit];
                _valiBT.enabled = NO;
                _valiBT.backgroundColor = [UIColor lightGrayColor];
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

- (IBAction)submitForm:(UIButton *)sender {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"plist"];
    
    NSString *mobileNo = _mobileTF.text;
    NSString *passwd = _passwdTF.text;
    if ( [mobileNo length] > 0 && [self validateMobile:mobileNo] && [passwd length] > 0 ) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *params = @{@"mobile": _mobileTF.text,
                                 @"password": _passwdTF.text,
                                 @"channel": @"3",
                                 @"apptype": @"1"};
        [manager POST:APIURL@"ucmembers/onRegister.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSString *jsonString = operation.responseString;
            self.logResult= responseObject;
            if ([_logResult valueForKey:@"result"]) {
                NSError* err = nil;
                ZPUserModel* userInfo = [[ZPUserModel alloc] initWithString:jsonString error:&err];
                NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
                [dataDic setValue:userInfo.userName  forKey:@"userName"];
                [dataDic setValue:userInfo.nickName forKey:@"nickName"];
                [dataDic setValue:_passwdTF.text forKey:@"passwd"];
                [dataDic setValue:userInfo.token forKey:@"token"];
                [dataDic setValue:userInfo.mobile forKey:@"mobile"];
                [dataDic setValue:userInfo.memberId forKey:@"memberId"];
                NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                NSString *plistPath1 = [paths objectAtIndex:0];
                
                //得到完整的文件名
                NSString *filename=[plistPath1 stringByAppendingPathComponent:@"UserInfo.plist"];
                
                [dataDic writeToFile:filename atomically:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
                regDoneViewController *regDoneVC = [self.storyboard instantiateViewControllerWithIdentifier:@"regDoneViewController"];
                [self.navigationController pushViewController:regDoneVC animated:YES];
            }else{
                if ([responseObject valueForKey:@"error"]) {
                    UIAlertView *errorInfo = [[UIAlertView alloc] initWithTitle:@"提示" message:responseObject[@"error"]  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [errorInfo show];
                    return;
                }
                UIAlertView *errorInfo = [[UIAlertView alloc] initWithTitle:@"提示" message:@"注册失败请重试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [errorInfo show];
            }
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView *errorInfo = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络，稍后重试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [errorInfo show];
        }];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                       message:@"请正确输入手机号码和验证码"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
        [alert show];
        return;
    }
}
@end
